<template>
  <div class="app-container">
    <el-row :gutter="10" class="el-row-inline">
      <el-col :span="4" :xs="24">
        <el-card style="height:100%">
          <div class="head-container">
            <el-input
              v-model="subjectName"
              placeholder="请输入学院/专业名称"
              clearable
              size="mini"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px; font-size: 12px;"
            />
          </div>
          <div class="head-container">
            <el-tree
              :data="subjectOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              default-expand-all
              highlight-current
              @node-click="handleNodeClick"
              style="font-size: 12px;"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <el-tooltip class="item" effect="dark" :content="node.label" placement="right">
                  <span class="tree-text">{{ node.label }}</span>
                </el-tooltip>
              </span>
            </el-tree>
          </div>
        </el-card>
      </el-col>

      <el-col :span="20" :xs="24">
        <el-card class="table-card">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['train:programTeachPlan:add']"
              >新增
              </el-button>
            </el-col>
          </el-row>

          <el-table
            v-loading="loading"
            :data="programTeachPlanList"
            border
            :span-method="objectSpanMethod"
            style="width: 100%; font-size: 11px;"
            size="mini"
            height="calc(100vh - 200px)"
            :cell-style="cellStyle"
          >
            <el-table-column
              label="课程平台"
              align="center"
              prop="coursePlatform"
              width="60"
            >
              <template slot-scope="scope">
                <dict-tag :options="dict.type.course_platform" :value="scope.row.coursePlatform"/> （{{scope.row.coursePlatformCredit}}）
              </template>
            </el-table-column>
            <el-table-column
              label="课程模块"
              align="center"
              width="80"
              prop="courseMainModule"
            >
              <template slot-scope="scope">
                <dict-tag :options="dict.type.course_main_module_credit" :value="scope.row.courseMainModule"/>（{{scope.row.courseMainModuleCredit}}）
              </template>
            </el-table-column>
            <el-table-column
              label="课程子模块"
              align="center"
              prop="courseChildrenModule"
              width="90"
            >
              <template slot-scope="scope">
                <dict-tag :options="dict.type.course_children_module" :value="scope.row.courseChildrenModule"/>
              </template>
            </el-table-column>
            <el-table-column
              label="修课要求"
              align="center"
              prop="studyRequire"
              width="70"
            >
              <template slot-scope="scope">
                <dict-tag :options="dict.type.study_require" :value="scope.row.studyRequire"/>（{{scope.row.studyRequireCredit}}）
              </template>
            </el-table-column>
            <el-table-column
              label="课程代码"
              align="center"
              prop="courseCode"
              width="80"
            />
            <el-table-column
              label="课程名称"
              align="center"
              prop="courseName"
              width="120"
            />
            <el-table-column
              label="学分"
              align="center"
              prop="creditComputed"
              width="50"
            />
            <el-table-column
              label="学时分配"
              align="center"
            >
              <el-table-column
                prop="totalHours"
                label="总学时"
                width="50"
              >
                <template slot-scope="scope">
                  {{ scope.row.totalHours + (scope.row.totalHoursUnit == null ? '' : scope.row.totalHoursUnit)}}
                </template>
              </el-table-column>
              <el-table-column
                prop="theoryHours"
                label="理论"
                width="50"
              >
              </el-table-column>
              <el-table-column
                label="实践"
                align="center"
              >
                <el-table-column
                  prop="experimentHours"
                  label="实验"
                  width="50"
                >
                  <template slot-scope="scope">
                  <span v-if="scope.row.experimentHoursUnit">{{
                      scope.row.experimentHours
                    }}{{ scope.row.experimentHoursUnit }}</span>
                    <span v-else>{{ scope.row.experimentHours }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="otherHours"
                  label="其他"
                  width="50"
                >
                </el-table-column>
              </el-table-column>
            </el-table-column>
            <el-table-column
              label="开课学期"
              align="center"
              prop="semesterStr"
              width="70"
            />
            <el-table-column
              label="启用状态"
              align="center"
              prop="isEnable"
              width="70"
            >
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_open_status" :value="scope.row.isEnable"/>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              fixed="right"
              width="100"
              class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['train:programTeachPlan:edit']"
                >修改
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['train:programTeachPlan:remove']"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>


    <!-- 添加或修改方案教学计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
<!--      <el-steps :active="active" finish-status="success">
        <el-step title="课程平台"></el-step>
        <el-step title="课程模块"></el-step>
        <el-step title="修课要求"></el-step>
        <el-step title="课程设置"></el-step>
      </el-steps>
      <el-button style="margin-top: 12px;" @click="next">下一步</el-button>-->

      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程平台" prop="coursePlatform">
              <el-select v-model="form.coursePlatform" placeholder="请选择课程平台">
                <el-option
                  v-for="dict in dict.type.course_platform"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程平台总学分" prop="coursePlatformCredit">
              <el-input v-model="form.coursePlatformCredit" placeholder="请输入课程平台总学分"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程主模块" prop="courseMainModule">
              <el-select v-model="form.courseMainModule" placeholder="请选择课程主模块">
                <el-option
                  v-for="dict in dict.type.course_main_module_credit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程主模块总学分" prop="courseMainModuleCredit">
              <el-input v-model="form.courseMainModuleCredit" placeholder="请输入课程主模块总学分"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程子模块" prop="courseChildrenModule">
              <el-select v-model="form.courseChildrenModule" placeholder="请选择课程子模块">
                <el-option
                  v-for="dict in dict.type.course_children_module"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="修读要求" prop="studyRequire">
              <el-select v-model="form.studyRequire" placeholder="请选择修读要求">
                <el-option
                  v-for="dict in dict.type.study_require"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="修读要求总学分" prop="studyRequireCredit">
              <el-input v-model="form.studyRequireCredit" placeholder="请输入修读要求总学分"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程" prop="courseId">
              <el-select v-model="form.courseId" placeholder="请选择课程" clearable>
                <el-option
                  v-for="item in courseList"
                  :key="item.id"
                  :label="item.courseName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程学分" prop="credit">
              <el-input v-model="form.credit" placeholder="请输入课程学分"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="总学时" prop="totalHours">
              <el-input v-model="form.totalHours" placeholder="请输入总学时"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总学时单位" prop="totalHoursUnit">
              <el-input v-model="form.totalHoursUnit" placeholder="请输入总学时单位，默认为空"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="理论学时" prop="theoryHours">
              <el-input v-model="form.theoryHours" placeholder="请输入理论学时"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开课学期" prop="semester">
<!--              <el-input v-model="form.semester" placeholder="请输入内容"/>-->
              <el-select v-model="form.semester" multiple placeholder="请选择开课学期">
                <el-option label="第一学期" :value="1"></el-option>
                <el-option label="第二学期" :value="2"></el-option>
                <el-option label="第三学期" :value="3"></el-option>
                <el-option label="第四学期" :value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="实验学时" prop="experimentHours">
              <el-input v-model="form.experimentHours" placeholder="请输入实验学时"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实验学时单位" prop="experimentHoursUnit">
              <el-input v-model="form.experimentHoursUnit" placeholder="请输入实验学时单位，默认为空"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="其他学时" prop="otherHours">
              <el-input v-model="form.otherHours" placeholder="请输入其他学时"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="isEnable">
              <el-radio-group v-model="form.isEnable">
                <el-radio
                  v-for="dict in dict.type.sys_open_status"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProgramTeachPlan,
  getProgramTeachPlan,
  delProgramTeachPlan,
  addProgramTeachPlan,
  updateProgramTeachPlan,
  getCourseListByProgramId
} from '@/api/train/programTeachPlan'
import { getTrainingProgramTree } from '@/api/train/trainingProgram'
import Treeselect from '@riophae/vue-treeselect'

export default {
  name: 'ProgramTeachPlan',
  components: { Treeselect },
  dicts: ['sys_open_status', 'course_children_module', 'course_platform', 'course_main_module_credit', 'study_require'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 方案教学计划表格数据
      programTeachPlanList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        programId: -1
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        programId: [
          { required: true, message: '方案ID不能为空', trigger: 'blur' }
        ],
        courseId: [
          { required: true, message: '课程Id不能为空', trigger: 'blur' }
        ],
        coursePlatform: [
          { required: true, message: '课程平台不能为空', trigger: 'change' }
        ],
        coursePlatformCredit: [
          { required: true, message: '课程平台总学分不能为空', trigger: 'blur' }
        ],
        courseMainModule: [
          { required: true, message: '课程主模块不能为空', trigger: 'change' }
        ],
        courseMainModuleCredit: [
          { required: true, message: '课程主模块总学分不能为空', trigger: 'blur' }
        ],
        studyRequire: [
          { required: true, message: '修读要求不能为空', trigger: 'change' }
        ],
        studyRequireCredit: [
          { required: true, message: '修读要求总学分不能为空', trigger: 'blur' }
        ],
        credit: [
          { required: true, message: '课程学分不能为空', trigger: 'blur' }
        ],
        totalHours: [
          { required: true, message: '总学时不能为空', trigger: 'blur' }
        ],
        theoryHours: [
          { required: true, message: '理论学时不能为空', trigger: 'blur' }
        ],
        isEnable: [
          { required: true, message: '是否启用：0-未启用  1-启用不能为空', trigger: 'change' }
        ]
      },
      subjectOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      subjectName: '',
      courseList: [],
      active: 0,
      mergeConfig: {
        labels: ['课程平台', '课程模块', '课程子模块', '修课要求', '课程代码', '课程名称', '学分'],
        subtotals: ['小计：', '合计：']
      }
    }
  },
  watch: {
    next() {
      if (this.active++ > 2) this.active = 0;
    },
    // 根据名称筛选部门树
    subjectName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.findTree().then(() => {
      this.getList();
    });
  },
  methods: {

    findTree() {
      return getTrainingProgramTree().then(res => {
        this.subjectOptions = res.data;
        // 如果不为空，取第一个子节点的值作为查询条件
        if (this.subjectOptions.length > 0) {
          this.queryParams.programId = this.subjectOptions[0].children[0].id;
          this.form.programId = this.queryParams.programId;
        }
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      // 可以点击父子级，所以需要打印出来看看结构再写逻辑
      if (data.children == null) {
        this.queryParams.programId = data.id;
        this.form.programId = data.id;
      }
      this.handleQuery();
    },
    /** 查询方案教学计划列表 */
    getList() {
      this.loading = true
      listProgramTeachPlan(this.queryParams).then(response => {
        this.programTeachPlanList = response.data
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        programId: null,
        courseId: null,
        coursePlatform: null,
        coursePlatformCredit: null,
        courseMainModule: null,
        courseMainModuleCredit: null,
        courseChildrenModule: null,
        studyRequire: null,
        studyRequireCredit: null,
        credit: null,
        totalHours: null,
        totalHoursUnit: null,
        theoryHours: null,
        experimentHours: null,
        experimentHoursUnit: null,
        otherHours: null,
        semester: null,
        isEnable: null,
        createTime: null,
        updateTime: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.findCourseListByProgramId()
      this.open = true
      this.title = '添加方案教学计划'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getProgramTeachPlan(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改方案教学计划'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.form.programId = this.form.programId || this.queryParams.programId
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProgramTeachPlan(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addProgramTeachPlan(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除方案教学计划编号为"' + ids + '"的数据项？').then(function() {
        return delProgramTeachPlan(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    findCourseListByProgramId() {
      getCourseListByProgramId(this.queryParams.programId)
        .then(res => {
          this.courseList = res.data;
        })
    },
    // 处理表格合并行和列
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 处理行合并
      if (columnIndex < 4) { // 处理前四列（课程平台、课程模块、课程子模块、学位要求）的行合并
        const rows = this.programTeachPlanList
        const fields = ['coursePlatform', 'courseMainModule', 'courseChildrenModule', 'studyRequire']
        const field = fields[columnIndex]

        // 获取当前字段的合并信息
        const spanArr = []
        let pos = 0

        rows.forEach((item, index) => {
          if (index === 0) {
            spanArr.push(1)
            pos = 0
          } else {
            // 判断当前行与上一行是否相同
            if (rows[index][field] === rows[index - 1][field] &&
                // 对于第二列和第三列，还需要检查前面的列是否相同
                (columnIndex === 0 ||
                 (columnIndex === 1 && rows[index]['coursePlatform'] === rows[index - 1]['coursePlatform']) ||
                 (columnIndex === 2 && rows[index]['courseMainModule'] === rows[index - 1]['courseMainModule'] &&
                                     rows[index]['coursePlatform'] === rows[index - 1]['coursePlatform']) ||
                 (columnIndex === 3 && rows[index]['courseChildrenModule'] === rows[index - 1]['courseChildrenModule'] &&
                                     rows[index]['courseMainModule'] === rows[index - 1]['courseMainModule'] &&
                                     rows[index]['coursePlatform'] === rows[index - 1]['coursePlatform']))) {
                spanArr[pos] += 1
                spanArr.push(0)
            } else {
                spanArr.push(1)
                pos = index
            }
          }
        })

        const span = spanArr[rowIndex]
        return {
          rowspan: span,
          colspan: span > 0 ? 1 : 0
        }
      }

      // 处理小计行的列合并
      const { labels, subtotals } = this.mergeConfig

      // 获取当前列的标签
      const currentLabel = this.getColumnLabel(column)
      // 检查是否是需要合并的列
      const mergeColumnIndex = labels.indexOf(currentLabel)

      // 检查当前行是否是小计行
      const isSubtotalRow = this.isSubtotalRow(row)

      if (isSubtotalRow) {
        // 如果是小计行且在合并范围内
        if (mergeColumnIndex !== -1) {
          // 如果是范围内的第一列，则合并
          if (mergeColumnIndex === 0) {
            return {
              rowspan: 1,
              colspan: labels.length
            }
          } else {
            // 其他列隐藏
            return {
              rowspan: 0,
              colspan: 0
            }
          }
        }
      }

      // 其他情况返回默认值
      return {
        rowspan: 1,
        colspan: 1
      }
    },

    // 获取列标签
    getColumnLabel(column) {
      return column.label
    },

    // 检查是否是小计行
    isSubtotalRow(row) {
      // 检查行中的任意字段是否包含小计标识
      return this.mergeConfig.subtotals.some(subtotal => {
        return Object.values(row).some(value =>
          typeof value === 'string' && value.includes(subtotal)
        )
      })
    },

    // 单元格样式
    cellStyle({ row, column }) {
      const isSubtotalRow = this.isSubtotalRow(row)
      if (isSubtotalRow) {
        return {
          'background-color': '#f5f7fa',
          'font-weight': 'bold',
          'text-align': 'center'
        }
      }
      return {}
    }
  },

}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.el-input-number {
  width: 100%;
}
.el-table {
  margin: 0 auto;
}
.el-table td {
  padding: 2px 0;
}
.el-table th {
  padding: 4px 0;
  font-size: 12px;
}
.el-button--mini {
  padding: 3px 8px;
  font-size: 11px;
}
.dialog-footer {
  text-align: right;
}
.custom-tree-node {
  width: 100%;
  .tree-text {
    display: inline-block;
    width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
